<?php
/**
 * Created by PhpStorm.
 * User: robert
 * Date: 2015/4/23
 * Time: 10:56
 */

class RedisUtil {


    private $redis_open,$redis_connect,$redis_port;

    /**
     * @throws Exception
     */
    function __construct()
    {

        $this->redis_open=getConfig("redis_open");

        if(!$this->redis_open){

            throw new Exception("不允许访问 redis 服务，如想访问，请修改 conf.php 配置");
        }

        $this->redis_connect=getConfig("redis_connect");
        $this->redis_port=getConfig("redis_port");

    }


    /**
     * 保存数据
     * @param $key
     * @param $value
     */
    public function set($key,$value){

        try{

            $redis = new Redis();

            $redis->connect($this->redis_connect,$this->redis_port);

            $redis->set($key,$value);


        }catch (Exception $e){

            print_r($e->getMessage());

        }
    }


    /**
     * 保存数据并设置数据有效期，时间单位（秒）
     * @param $key
     * @param $value
     * @param $timeout
     */
    public function set_with_timeout($key,$value,$timeout){

        try{

            $redis = new Redis();

            $redis->connect($this->redis_connect,$this->redis_port);

            $redis->setex($key,$timeout,$value);


        }catch (Exception $e){

            print_r($e->getMessage());

        }

    }


    /**
     * 获取数据
     * @param $key
     * @return bool|string
     */
    public function get($key){

        try{

            $redis = new Redis();

            $redis->connect($this->redis_connect,$this->redis_port);

            return $redis->get($key);

        }catch (Exception $e){

            print_r($e->getMessage());

            return "";

        }

    }


    /**
     * 清除数据
     * @param $key
     * @return null|string
     */
    public function clean($key){

        try{

            $redis = new Redis();

            $redis->connect($this->redis_connect,$this->redis_port);

            $redis->del($key);

        }catch (Exception $e){

            print_r($e->getMessage());

            return "";

        }

        return null;

    }

}